<template>
  <el-dialog append-to-body
             :close-on-click-modal="false"
             :title="title"
             :visible.sync="syncVisible"
             width="800px"
             @close="doCancel"
             @open="doOpen"
             v-el-drag-dialog>
    <div v-loading="syncedTableOptions.loading">
      <header class="py-2 px-1 d-flex">
        <div class="ms-auto mt-auto">
          <el-input class="align-middle ipt-search mx-1"
                    placeholder="关键字"
                    v-model="syncedFilter.searchKey"></el-input>
          <el-button class="mx-1"
                     icon="el-icon-search"
                     type="primary"
                     @click.stop="onSearch">查询</el-button>
          <el-button class="mx-1"
                     plain
                     @click.stop="doResetFilter">重置</el-button>
        </div>
      </header>
      <div>
        <vxe-table ref="tbl"
                   :id="cacheId"
                   auto-resize
                   border
                   :column-config="{resizable: true}"
                   :custom-config="{storage:{resizable:cacheId}}"
                   :data="syncedTableOptions.data"
                   height="400"
                   :resizable-config="{minWidth:40}"
                   round
                   :row-config="{isHover: true,keyField:syncedTableOptions.rowKey }"
                   :scroll-y="{gt: 100,scrollToTopOnChange:true}"
                   show-header-overflow="tooltip"
                   show-overflow="tooltip"
                   stripe
                   @cell-dblclick="doToggleSelect"
                   @checkbox-all="({records}) => $emit('selection-change',records)"
                   @checkbox-change="({records}) => $emit('selection-change',records)"
                   @checkbox-range-end="({records}) => $emit('selection-change',records)"
                   @radio-change="doRadioChange">
          <vxe-column align="center"
                      fixed="left"
                      :resizable="false"
                      :show-header-overflow="false"
                      :show-overflow="false"
                      type="seq"
                      width="40"></vxe-column>
          <vxe-column v-if="multiple"
                      align="center"
                      fixed="left"
                      :resizable="false"
                      :show-header-overflow="false"
                      :show-overflow="false"
                      type="checkbox"
                      width="40"></vxe-column>
          <vxe-column v-else
                      align="center"
                      fixed="left"
                      :resizable="false"
                      :show-header-overflow="false"
                      :show-overflow="false"
                      title="选择"
                      type="radio"
                      width="40"></vxe-column>
          <slot></slot>
          <template #empty>
            <el-empty class="p-0"
                      description="无可用数据">
              <el-button plain
                         type="primary"
                         @click.stop="onSearch">
                <ju-icon class="me-2"
                         icon="el-icon-refresh"></ju-icon>刷新重试
              </el-button>
            </el-empty>
          </template>
        </vxe-table>
      </div>
      <footer class="py-2 px-1 d-flex">
        <div class="ms-auto">
          <el-pagination background
                         :current-page.sync="syncedTableOptions.currentPage"
                         :disabled="syncedTableOptions.loading"
                         layout="total, sizes, prev, pager, next, jumper"
                         :page-size.sync="syncedTableOptions.pageSize"
                         :page-sizes="syncedTableOptions.pageSizes"
                         :total="syncedTableOptions.total">
          </el-pagination>
        </div>
      </footer>
    </div>
    <template #footer>
      <div class="text-end dialog-footer">
        <el-badge :hidden="!selectedRows.length"
                  :is-dot="!multiple"
                  :max="99"
                  :value="selectedRows.length">
          <el-popover placement="top">
            <el-button slot="reference"
                       :disabled="syncedTableOptions.loading || !selectedRows.length"
                       plain
                       type="danger">
              查看已选
            </el-button>
            <div class="overflow-auto"
                 style="width:250px;max-height:300px;">
              <ol class="m-0 py-1 pe-1">
                <li v-for="(item,index) in selectedRows"
                    :key="`selected-items-${item[syncedTableOptions.rowKey]}`">
                  <div class="d-flex align-items-center">
                    <div class="flex-grow-1 text-nowrap overflow-hidden text-ellipsis">
                      {{ item[textField] }}
                    </div>
                    <el-link class="remove-item-icon"
                             type="danger"
                             :underline="false"
                             @click.stop="doRemoveSelected(item,index)">
                      <ju-icon icon="x"
                               svg-icon></ju-icon>
                    </el-link>
                  </div>
                </li>
              </ol>
            </div>
          </el-popover>
        </el-badge>
        <el-button :disabled="syncedTableOptions.loading"
                   type="primary"
                   @click.stop="doComplete">
          <ju-icon class="me-1 align-bottom"
                   icon="check-all"
                   svg-icon />确认选择
        </el-button>
        <el-button type="default"
                   @click.stop="doCancel">
          <ju-icon class="me-1 align-bottom"
                   icon="arrow-return-left"
                   svg-icon />取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
  import { Component, PropSync, Vue, Prop, Watch } from "@some21/vue-class-decorator";
  import { cloneDeep } from "lodash";
  import dayjs from "dayjs";
  import { createFilterData, createTableOptions } from "@/framework/models/TableOptions";

  @Component({
    name: "DialogSelected",
  })
  export default class extends Vue {
    $refs: {
      tbl: import("vxe-table").Table;
    };
    private __DEF_FILTER__ = null;

    @PropSync("visible", { default: false, type: Boolean })
    syncVisible: boolean;
    @Prop({ default: "选择数据", type: String })
    title: string;
    @Prop({ type: Boolean, default: false })
    multiple: boolean;

    @Prop({ type: String, default: false })
    textField: String;

    @Prop({ type: String })
    cacheId: string;
    @PropSync("filter", { type: Object, default: createFilterData() })
    syncedFilter: ReturnType<typeof createFilterData>;
    @PropSync("tblOptions", { type: Object, default: createTableOptions() })
    syncedTableOptions: ReturnType<typeof createTableOptions>;
    @Prop({ type: [Array, Number], default: [] })
    defSelected: any;

    @Watch("tblOptions.currentPage")
    @Watch("tblOptions.pageSize")
    onPageInfoChange() {
      this.$emit("page-change");
    }
    @Watch("tblOptions.data")
    async onTableDataChange(data) {
      if (data && data.length) {
        if (this.multiple) {
          const checkedRows = data.filter(f => this.defSelected.some(s => s === f[this.syncedTableOptions.rowKey]));
          if (checkedRows.length) {
            await this.$refs.tbl.setCheckboxRow(checkedRows, true);
          }
        } else {
          const selectedRow = data.filter(f => this.defSelected === f[this.syncedTableOptions.rowKey]);

          if (selectedRow.length) {
            await this.$refs.tbl.setRadioRow(selectedRow[0]);
          }
        }
      }
    }

    selectedRows = [];

    lastRefreshTime;

    doOpen() {
      this.__DEF_FILTER__ = cloneDeep({ ...createFilterData(), ...this.syncedFilter }); // 深拷贝
      this.syncedTableOptions = { ...createTableOptions(), ...this.syncedTableOptions };

      this.onSearch();
    }
    doComplete() {
      this.$emit("confirm", this.selectedRows);
      this.syncVisible = false;
    }
    doCancel() {
      this.syncVisible = false;
    }
    onSearch() {
      // 判断上次刷新时间和本次操作刷新时间间隔是否小于N 秒，若小于N秒，则提示限流
      // 若为翻页操作，则不触发限流提示
      // 阀值暂定 1.5 秒，依据实际情况进行调整
      const threshold = 1.2;
      if (this.lastRefreshTime && dayjs().diff(this.lastRefreshTime, "seconds", true) <= threshold) {
        this.$message.warning({ message: "您的操作太快啦，喝口水休息下吧！", showClose: true });
        return;
      }
      this.lastRefreshTime = new Date();
      this.$emit("search", this.syncedFilter);
    }

    // 重置筛选条件
    doResetFilter() {
      this.syncedFilter = cloneDeep(this.__DEF_FILTER__);
    }
    async doRadioChange({ row }) {
      this.selectedRows = [row];
    }
    async doToggleSelect({ row, records }) {
      // 切换当前行的选中状态
      if (this.multiple) {
        // 切换当前行选中状态
        this.$refs.tbl.toggleCheckboxRow(row);
        this.selectedRows = records;
      } else {
        this.selectedRows = [row];
        await this.$refs.tbl.setRadioRow(row); // 设定选中行
      }
    }
    doRemoveSelected(item, index) {
      debugger;
    }

    // async doLayout() {
    //   await this.$refs.tbl.recalculate();
    // }
  }
</script>

<style lang="scss" scoped>
  .ipt-search {
    width: 180px;
  }
  .dialog-footer {
    margin: 0 -10px;
    > * {
      margin: 0 0.25rem;
    }
  }
  .remove-item-icon {
    transition: all 0.2s;
    &:hover {
      transform: rotate(180deg);
    }
  }
</style>
